<!DOCTYPE html>
<html lang=''>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <script src='./vue.js'></script>
</head>

<body>
    <div id='app'>
        <div>
            爷爷组件
            <father></father>
        </div>
    </div>
</body>
<script>

    const { provide, inject, ref } = Vue
    // provide：依赖，可以将数据和方法进行发射出去
    // inject：注入，可以接收数据和方法，如果是方法可以直接调用
    const son = {
        template: `<div> 孙子 {{msg}}  组件 <button @click='btnClick'>修改传家宝</button> </div>`,
        setup () {

            const msg = inject('msg')
            const changeMsg = inject('changeMsg')

            function btnClick () {
                console.log('被点击了');
                changeMsg('下课时间到')
            }

            return {
                msg,
                btnClick
            }
        }
    }

    const father = {
        template: `<div> 父 {{ message }} 组件 -- <son></son> </div>`,
        setup () {
            const message = inject('msg')

            return {
                message
            }
        },
        components: {
            son
        }
    }



    const app = Vue.createApp({
        setup (props, context) {

            const msg = ref('传家宝')

            function changeMsg (val) {
                msg.value = val
            }

            // 发射数据，将数据共享出去
            provide('msg', msg)
            provide('changeMsg', changeMsg)

            return {}
        },
        components: {
            father
        }
    })
    app.mount('#app')
</script>

</html>